package glory.xxd

import org.apache.commons.lang.StringEscapeUtils
import org.json.JSONObject
import org.json.XML

/**
 * 数据格式转换工具类
 * Created by Administrator on 2018-01-22.
 */
class Utils {


    static String getUUID() {
        return java.util.UUID.randomUUID()
    }

    static String getValueByXML(String xml, String property) {

        def responseInstance = new XmlParser().parseText(xml)// new XmlParser().parseText(aa)
        def body = responseInstance.Body
        def str = body."${property}".text()
        return str ?: ""
    }

    static String getValueByXML(groovy.util.Node node, String property) {
        def body = node.Body
        def str = body."${property}".text()
        return str ?: ""
    }

    static String getJsonByXML(String xml) {
        def json = org.json.XML.toJSONObject(xml)
        return json
    }

    /**
     *
     * @param xml
     * @param nodeName
     * @return
     */
    static String getJsonByXML(String xml, String nodeName) {
        def json =XML.toJSONObject(xml)
        def nodes = nodeName.split('/.')
        nodes.each { it ->
            json = json."${it}"
        }
        return json.toString()
    }

    /**
     *
     * @param xml
     * @param nodeName
     * @return
     */
    static JSONObject getJsonObjectByXML(String xml, String nodeName) {
        def json = org.json.XML.toJSONObject(xml)
        def nodes = nodeName.split('/.')
        //[Request,Body]
        nodes.each { it ->
            json = json."${it}"
        }
        return json
    }

    static String getXmlByJSON(Object obj) {
        def xml
        if (obj) {
            JSONObject jsonObject = new JSONObject(obj)
            xml = XML.toString(jsonObject)
        }

        return xml
    }

    /**
     *
     * @param obj
     * @return
     */
    static String getXmlByJSONHtml(Object obj) {
        def xml
        if (obj) {
            JSONObject jsonObject = new JSONObject(obj)
            xml = XML.toString(jsonObject)
            xml = StringEscapeUtils.unescapeHtml(xml)
        }

        return xml
    }

}